package com.hospital.register.core.service.impl;

import com.hospital.register.common.exception.BusinessException;
import com.hospital.register.common.result.ResultCodeEnum;
import com.hospital.register.constants.BaseEntityConstants;
import com.hospital.register.core.repository.DepartmentRepository;
import com.hospital.register.core.service.DepartmentService;
import com.hospital.register.core.service.ScheduleService;
import com.hospital.register.dto.core.api.DepartmentPageDto;
import com.hospital.register.model.core.Department;
import com.hospital.register.vo.core.api.DepartmentPageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    /**
     * 访问科室数据
     */
    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 处理排班相关业务
     */
    @Autowired
    private ScheduleService scheduleService;

    @Override
    public boolean exists(String hoscode, String depcode) {
        return this.departmentRepository.exists(hoscode, depcode);
    }

    @Override
    public boolean insert(Department department) {
        Date now = new Date();
        department.setCreateTime(now);//创建时间
        department.setUpdateTime(now);//更新时间
        department.setIsDeleted(BaseEntityConstants.NOT_DELETED);//未删除
        return this.departmentRepository.insert(department);
    }

    @Override
    public boolean update(Department department) {
        department.setUpdateTime(new Date());
        department.setIsDeleted(BaseEntityConstants.NOT_DELETED);//未删除
        return this.departmentRepository.update(department);
    }

    @Override
    public Page<DepartmentPageVo> findPage(DepartmentPageDto dto) {
        return this.departmentRepository.findPage(dto);
    }

    @Override
    public boolean remove(String hoscode, String depcode) {
        boolean hadFutureSchedule = this.scheduleService.existInFuture(hoscode, depcode);
        if (hadFutureSchedule) {
            throw new BusinessException("抱歉，该科室下存在上未执行的排班，不可删除", ResultCodeEnum.DATA_ERROR.getCode());
        }
        return this.departmentRepository.remove(hoscode, depcode);
    }

    @Override
    public List<Department> findByHoscode(String hoscode) {
        return this.departmentRepository.findByHoscode(hoscode);
    }

    @Override
    public Department findOne(String hoscode, String depcode) {
        return this.departmentRepository.findOne(hoscode, depcode);
    }

}
